package com.eorchis.module.classcourse.ui.controller;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.commond.converter.IQueryCommondAttributeConverter;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.classcourse.domain.ClassCourse;
import com.eorchis.module.classcourse.domain.ClassCourseExport;
import com.eorchis.module.classcourse.domain.ClassCourseSheet;
import com.eorchis.module.classcourse.domain.ExportClassCourseBean;
import com.eorchis.module.classcourse.querybean.ClassCourseQueryBean;
import com.eorchis.module.classcourse.service.IClassCourseService;
import com.eorchis.module.classcourse.ui.commond.ClassCourseQueryCommond;
import com.eorchis.module.classcourse.ui.commond.ClassCourseValidCommond;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.module.user.domain.User;
import com.eorchis.utils.excelutil.ExcelIO;
import com.eorchis.utils.excelutil.ExcelIOFactory;
import com.eorchis.utils.excelutil.export.bo.Sheet;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: ClassCourseController<br>
 * Description: 班级课程维护管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Max
 * @createDate 2014-12-11
 * @version $Revision$
 */
@Controller("classCourseController")
@RequestMapping(value = ClassCourseController.MODULE_PATH)
public class ClassCourseController 
		extends AbstractBaseController<ClassCourseValidCommond,ClassCourseQueryCommond> 
{
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/classcourse";
	// 班级课程维护接口
	@Autowired
	@Qualifier("com.eorchis.module.classcourse.service.impl.ClassCourseServiceImpl")
	private IClassCourseService classCourseService;
	
	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
	private ITrainingClassService trainingClassService;
	
	@Autowired
	@Qualifier("attributeConverter")
	private ArrayList<IQueryCommondAttributeConverter> attributeConverter;
	
	public IBaseService getService() {
		return classCourseService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}
	
	/**
	 * 查询课程列表
	 * @param qCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-11
	 */
	@RequestMapping(value = "/findClassCoursePageList")
	public String findClassCoursePageList(
			@ModelAttribute("resultList") ClassCourseQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		if (attributeConverter != null) {
			parameterValueConvert(qCommond, request, attributeConverter);
		}
		//执行查询逻辑 
		List<ClassCourseQueryBean> resultList = classCourseService.findClassCoursePageList(qCommond);
		//存放结果
		qCommond.setResultList(resultList);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return getModulePath() + "/list";
	}
	
	
	/**
	 * 查询课程列表
	 * @param qCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-11
	 */
	@RequestMapping(value = "/findClassCourseAllList")
	public String findClassCourseAllList(
			@ModelAttribute("resultList") ClassCourseQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		if (attributeConverter != null) {
			parameterValueConvert(qCommond, request, attributeConverter);
		}
		//执行查询逻辑 
		//List<ClassCourseQueryBean> resultList = classCourseService.findClassCourseAllList(qCommond);
		List<ClassCourseQueryBean> resultList = classCourseService.findClassCoursePageList(qCommond);
		//存放结果
		qCommond.setResultList(resultList);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return getModulePath() + "/list";
	}
	/**
	 * 导出课程信息列表
	 * @param qCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @createDate 2014-1-5
	 */
	@RequestMapping(value = "/exportClassCourseAllList")
	public void exportClassCourseAllList(
			@ModelAttribute("resultList") ClassCourseQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
/*		if (attributeConverter != null) {
			parameterValueConvert(qCommond, request, attributeConverter);
		}*/
		//执行查询逻辑 
		List<ClassCourseQueryBean> resultList = classCourseService.findClassCourseAllList(qCommond);
		//List<ClassCourseQueryBean> resultList = classCourseService.findClassCoursePageList(qCommond);
		//存放结果
		List<ExportClassCourseBean> exportBeans=new ArrayList<ExportClassCourseBean>();
		ExportClassCourseBean exportBean=null;
		for(ClassCourseQueryBean queryBean:resultList){
			exportBean=new ExportClassCourseBean();
			exportBean.setCourseName(queryBean.getCourseName());
			//exportBean.setCourseNum(queryBean.getCourseNum());
			exportBean.setSpeaker(queryBean.getSpeaker());
			exportBean.setSpeakdept(queryBean.getSpeakdept());
			exportBean.setSpeakway(queryBean.getSpeakwayStr());
			exportBean.setSpeakDateStr(queryBean.getSpeakDate());
			exportBean.setSpeakTime(queryBean.getSpeakTimeStr());
			exportBean.setSpeakDuty(queryBean.getSpeakDuty());
			exportBeans.add(exportBean);
		}
		ClassCourseExport courseExport = new ClassCourseExport();
		courseExport.setExportClassCourseBean(exportBeans);
		ClassCourseSheet courseSheet = new ClassCourseSheet();
		courseSheet.setExportObject(courseExport);
		courseSheet.setExprotFormatName("ClassCourseExportConfig");
		courseSheet.setSheetName("课程列表");
		Sheet[] sheetArray = new Sheet[] { courseSheet };// 导出Excel的Sheet集合
		ExcelIO excelio = ExcelIOFactory.getExcelIO();// Excel导出工具
		String title="课程表";
		response.setContentType("application/msexcel;charset=ISO8859-1");
		response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
		OutputStream out = response.getOutputStream();
		excelio.exportExcel(out, "resumeExportStyle", sheetArray, false);
	}
	/**
	 * 执行查询课程
	 * @param commond
	 * @param bindingResult
	 * @param request
	 * @param response
	 * @param resultState 
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-10
	 */
	@RequestMapping(value = "/findCourseInfo")
	public String findCourseInfo(@ModelAttribute("result") @Valid ClassCourseValidCommond vCommond,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		
		String courseId=vCommond.getClassCourseId();
		if(PropertyUtil.objectNotEmpty(courseId)) {
			ClassCourseValidCommond co=this.getService().find(courseId);
			BeanUtils.copyProperties(co,vCommond);
			ClassCourse course=(ClassCourse) co.toEntity();
			if(course.getSpeakway()!=null) {
				vCommond.setSpeakway(course.getSpeakway().getDataCode());
			}
			if(course.getSpeakDate()!=null){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				vCommond.setSpeakDateStr(sdf.format(course.getSpeakDate()));
			}
			if(course.getSpeakTime()!=null){
				vCommond.setSpeakTime(course.getSpeakTime().getDataCode());
			}
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else {
			resultState.setMessage("课程ID为空");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	
	
	/**
	 * 执行添加培训班课程的逻辑
	 * @param commond
	 * @param bindingResult
	 * @param request
	 * @param response
	 * @param resultState 
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-09
	 */
	@RequestMapping(value = "/addCourse")
	public String addCourse(@ModelAttribute("result") @Valid ClassCourseValidCommond vCommond,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		if(token.isTokenValid(request, true)){//判断token
			ClassCourse course= (ClassCourse) vCommond.toEntity();
			TrainingClassValidCommond co=trainingClassService.find(vCommond.getClassId());
			TrainingClass tc=(TrainingClass) co.toEntity();
			//添加班级对象
			course.setTrainingClass(tc);
			//拼凑课件编号
			/*vCommond.setSearchCourseNum(tc.getClassNum());
			String num=classCourseService.getMaxCourseNum(vCommond);
			vCommond.setCourseNum(num);*/
			//添加课程类型
			BaseData ba=new BaseData();
			ba.setDataCode(vCommond.getSpeakway());
			course.setSpeakway(ba);
			//添加授课时间
			BaseData bd=new BaseData();
			bd.setDataCode(vCommond.getSpeakTime());
			course.setSpeakTime(bd);
			vCommond.setCreateDate(new  Date());
			
			//处理课程评估时间
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        Date endDate = tc.getEndDate();
	        Calendar StartTime = Calendar.getInstance();
	        StartTime.setTime(endDate);
	        StartTime.add(Calendar.DAY_OF_YEAR,-1);//日期加10天
	        Date courseAssessStartTime=StartTime.getTime();
	        Calendar endTime = Calendar.getInstance();
	        endTime.setTime(endDate);
	        endTime.add(Calendar.DAY_OF_YEAR,2);//日期加10天
	        Date courseAssessEndTime=endTime.getTime();
			vCommond.setCourseAssessStartTime(courseAssessStartTime);
			vCommond.setCourseAssessEndTime(courseAssessEndTime);
			
			getService().save(vCommond);
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("添加成功");
		}else{
			resultState.setState(ResultState.RESULT_STATE_REPEAT_SUBMIT);//重复提交
			resultState.setMessage("重复提交");
		}
		return "forward:"+getModulePath()+"/findList"+getRequestType(request);
	}
	
	
	/**
	 * 修改课程信息
	 * Description: <br>
	 * @author Max
	 * @createDate 2014-12-15
	 * @version $Revision: $
	 */
	@RequestMapping(value = "/updateCourse")
	public String updateCourse(
			@ModelAttribute("result") ClassCourseValidCommond vCommond,HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception{
		try{
			classCourseService.updateCourse(vCommond);
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("修改成功");
		}catch(Exception e){
			resultState.setState(ResultState.RESULT_STATE_FAIL);
			resultState.setMessage("修改失败");
			e.printStackTrace();
			throw e;
		}
		return "";
	}
	
	
	@RequestMapping(value = "/deleteCourse")
	public String deleteCourse(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState) throws Exception{
		//获取删除课程的所有学时
		//Double studyScore=classCourseService.getstudyScore(request.getParameterValues("ids"));
		getService().delete(request.getParameterValues("ids"));
		/*//执行学分修改操作
		String classId=request.getParameter("classId").toString();
		TrainingClassValidCommond co=trainingClassService.find(classId);
		TrainingClass tc=(TrainingClass) co.toEntity();
		Double hour=0.0;
		if(tc.getTrainingHour()!=null) {
			hour=tc.getTrainingHour()-studyScore;
		}
		trainingClassService.updateStudyHour(hour, classId);
		
		if(tc.getAuditState().equals(TrainingClass.IS_AUDIT_N)) {
			trainingClassService.updateCState(tc.getClassId());
		}*/
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);//设置成功状态
		return "forward:"+getModulePath(request)+"/findList"+getRequestType(request);
	}

	
	/**
	 * @return Excel导入课程
	 * @throws Exception
	 * @author Max
	 * @date 2014-12-25
	 *//*
	@RequestMapping(value = "/importCourse")
	public String importCourseForExcel(HttpServletRequest request,@ModelAttribute("ResultSate")ResultState resultState,
			@ModelAttribute("resultList") ClassCourseValidCommond vCommond)throws Exception{
			String msg="";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (MultipartFile mf : fileMap.values()) {
				CommonsMultipartFile cmf = (CommonsMultipartFile) mf;
				FileItem file = cmf.getFileItem();
				//File file = new File("D:\\导入课程模板.xls");  
		       // FileInputStream item = new FileInputStream(file); 
				String name = file.getName();
				//byte[] bytes = null;
				if (name == null || name.trim().equals("")) {
					msg = "您使用的导入模板不正确，请确认后重新导入。";
				} else {
					String fileType = name.substring(name.lastIndexOf("."));
					if (!".xls".equals(fileType)) {
						//msg = "导入失败！\r\n上传格式错误！只能上传后缀为.xls的文件";
						msg="导入文件格式错误，应为.xls格式，请修改后重新导入。";
					} else {
						byte[] bytes = mf.getBytes();
//						ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
//			            byte[] b = new byte[1000];  
//			            int n;  
//			            while ((n = item.read(b)) != -1) {  
//			                bos.write(b, 0, n);  
//			            }  
//			            item.close();  
//			            bos.close();  
//			            bytes = bos.toByteArray();
						if (bytes.length == 0) {
							msg = "您使用的导入模板不正确，请确认后重新导入。";
						} else {
							//写解析bytes代码
							InputStream in = null;
							ExcelSheet sheet = null;
							in = new ByteArrayInputStream(bytes);
							//读取excel
							sheet=excelUtils.readFile(in);
							if(PropertyUtil.objectNotEmpty(sheet)){
								msg=classCourseService.importCourseForExcel(vCommond, sheet);
							}else {
								msg = "您使用的导入模板不正确，请确认后重新导入。";
							}
						}
					}
				}
			}
			if ("".equals(msg)) {
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				resultState.setMessage("导入成功！");
			} else {
				resultState.setState(ResultState.RESULT_STATE_FAIL);
				resultState.setMessage(msg);
			}
		return "";
	}*/
	
	/**
	 * @return Excel导入课程
	 * @throws Exception
	 * @author Max
	 * @date 2014-12-25
	 */
	@RequestMapping(value = "/importCourse")
	public String importCourseForExcel(Model model,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("ResultSate")ResultState resultState,
			@ModelAttribute("resultList") ClassCourseValidCommond vCommond)throws Exception{
		resultState.setState(ResultState.RESULT_STATE_FAIL);// 默认失败
		String msg = "";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (MultipartFile mf : fileMap.values()) {
			CommonsMultipartFile cmf = (CommonsMultipartFile) mf;
			FileItem file = cmf.getFileItem();
			if (!(file.isFormField())) { // 确认来源为文件域上传
				String name = file.getName();
				if (name == null || name.trim().equals(""))
					msg = "您使用的导入模板名称不正确，请确认后重新导入！";
				else if (file.getSize() == 0L)
					msg = "您使用的导入模板不正确，请确认后重新导入！";
				else {
					String fileType = name.substring(name.lastIndexOf("."));
					if (!".xls".equals(fileType))
						msg = "导入文件格式错误，应为.xls格式，请修改后重新导入！";
					else {
						try {
							// 调用service批量导入的方法
							msg = classCourseService.importCourseForExcel(vCommond,file, response, request);
							if ("failure".equals(msg))
								msg = "系统出错，导入失败！";
							else if (msg.equals("导入成功"))
								resultState.setState(ResultState.RESULT_STATE_SUCCESS);
						} catch (Exception e) {
							e.printStackTrace();
							msg = "系统出错，导入失败！";
						}
					}
				}
			}
		}
		resultState.setMessage(msg);
		return "";
	}
	/**
	 * 用于排序的方法
	 * @param queryCommond
	 * @param request
	 * @param attributeConverter
	 */
	@SuppressWarnings("unchecked")
	private void parameterValueConvert(ClassCourseQueryCommond queryCommond,
			HttpServletRequest request,
			List<IQueryCommondAttributeConverter> attributeConverter) {
		for (IQueryCommondAttributeConverter queryCommondAttributeConverter : attributeConverter) {
			queryCommondAttributeConverter.convert(queryCommond,
					request.getParameterMap());
		}
	}
	
	/**
	 * 查询班级课程列表
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author RongSL
	 * @date 2016-05-20
	 */
	@RequestMapping(value = "/findAssessCourseList")
	public String findAssessCourseList(@ModelAttribute("resultList") ClassCourseQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response, @ModelAttribute("resultState") ResultState resultState) throws Exception {
		if (attributeConverter != null)
			parameterValueConvert(qCommond, request, attributeConverter);
		// 执行查询逻辑
		qCommond.setUserId(((User) request.getSession().getAttribute(SessionConstant.USER_INFO)).getUserId());
		List<ClassCourseQueryBean> resultList = classCourseService.findAssessCourseList(qCommond);
		// 存放结果
		qCommond.setResultList(resultList);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return getModulePath() + "/list";
	}
	
	/**
	 * 删除课程问卷
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @throws Exception
	 * @author RongSL
	 * @createDate 2016-5-24
	 */
	@RequestMapping(value = "/deleteCourseQuestionnaire")
	public String deleteCourseQuestionnaire(@ModelAttribute("result") ClassCourseValidCommond validCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		if (PropertyUtil.objectNotEmpty(validCommond.getCourseIds())) {
			classCourseService.deleteCourseQuestionnaire(validCommond);
			resultState.setMessage("删除成功");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} else {
			resultState.setMessage("缺少参数");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
}
